<template>
  <div class="shopCarGift">
    <div class="left" ref="goodsWrap">
      <div class="needGoods" @click="$router.push({name: 'wishList'})">
        <img src="@/assets/images/needGoods2.png" alt="img">
      </div>
        <div class="goodsList" ref="goodsBox">
          <ul class="title">
            <li v-for="(item, index) in sortArr" :key="index">
              <span>{{ item.title + ((item.value == sortActive.split('-')[0]) ? (sortActive.split('-')[1] == 'desc' ? '由高到低' : '由低到高') : '') }}</span>
              <strong>
                <i @click="checked(item.name[0])" :class="{ 'active': item.name[0] == sortActive }" class="top"></i>
                <i @click="checked(item.name[1])" :class="{ 'active': item.name[1] == sortActive }" class="bottom"></i>
              </strong>
            </li>
          </ul>
          <noCont v-if="goodsArr.length == 0"></noCont>
          <ul v-if="goodsArr.length > 0" class="goodsInfo">
            <li v-for="(item, index) in goodsArr" :key="index">
              <div class="imgBox">
                <img @click="lookImg(item.picList ? JSON.parse(item.picList)[0] : noImg)" :src="item.picList ? JSON.parse(item.picList)[0] : noImg" alt="商品主图">
            </div>
                <p :title="item.description">{{ item.description }}</p>
                <div class="bottom">
                  <div class="count">
                    <i class="iconfont">￥</i><strong class="iconfont">{{ item.price.toFixed(2) }}</strong>
                    <span>{{ item.weight }}kg</span>
                  </div>
                  <div class="joinCar" @click="addPackage(item)">
                    <i></i>
                  </div>
                </div>
            </li>
            <li class="empty" v-for="(item, index) in emptyNum" :key="index"></li>
          </ul>
          <div v-if="goodsArr.length > 0" class="pager">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo" :page-size="pageSize" :page-sizes="[20, 40, 60, 120]" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
            </el-pagination>
            <div class="toTop" @click="toTop">
              <i class="el-icon-arrow-up"></i>
              <span>TOP</span>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="titles">
          <span>产品</span>
          <span>单价</span>
          <span>重量</span>
          <span>数量</span>
          <span>总价</span>
        </div>
        <ul class="chooseList" v-if="checkedArr.length > 0">
          <li v-for="(item, index) in checkedArr" :key="index">
            <div>
              <img :src="item.picList ? JSON.parse(item.picList)[0] : noImg" alt="img">
          </div>
              <div>
                <span>￥{{ item.price }}</span>
              </div>
              <div>
                <span>{{ item.weight }}kg</span>
              </div>
              <div class="count">
                <i class="el-icon-remove" @click="dele(item, index)"></i>
                <input type="number" v-model="item.num">
                <i class="el-icon-circle-plus" @click="add(item, index)"></i>
              </div>
              <div>
                <span>￥{{ (item.price * item.num).toFixed(2) }}</span>
              </div>
              <i @click="deleChecked(index)" class="dele el-icon-circle-close-outline"></i>
          </li>
        </ul>
        <div v-if="checkedArr.length == 0" class="noCont">
          <img class="noCont" src="@/assets/images/noContainer.svg" alt="noCont">
        </div>
          <!-- <div class="countMoneyBox mt120" :class="{'mt120': checkedArr.length < 4 }"> -->
          <div class="countMoneyBox mt120">
            <p>
              <span>商品总额：</span>
              <strong>￥{{ totalObj.priceTotal }}</strong>
            </p>
            <p>
              <span>运费(
                <i>{{ totalObj.weightTotal }}kg</i>)：</span>
              <strong>￥{{ logisticPrice }}</strong>
            </p>
            <p class="total">
              <span>总计：</span>
              <strong>￥{{ ((logisticPrice - 0) + (totalObj.priceTotal - 0)).toFixed(2) }}</strong>
            </p>
          </div>
          <div class="operateBtn">
            <p>
              <span @click="toSamApplay">样品申请</span>
              <strong @click="goWhere('ordersNow')">立即采购</strong>
            </p>
            <div class="setCommon" @click="setCommonPackage">设为常用礼品包</div>
          </div>
        </div>
      </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'shopCar',
  computed: {
    emptyNum () {
      if (this.goodsArr) {
        let allNum = this.goodsArr.length
        let num = 0
        num = allNum % 4
        return (4 - num)
      }
    },
    logisticPrice () {
      let weight = this.totalObj.weightTotal
      let priceObj = this.logisticList
      let logisticMoney = 0
      if (weight > 0 && weight <= 0.5) {
        logisticMoney = priceObj.firstPrice
      } else if (weight > 0.5 && weight <= 1) {
        logisticMoney = priceObj.middlePrice
      } else if (weight > 1) {
        logisticMoney = (1 * priceObj.middlePrice + (Math.ceil(weight - 1)) * priceObj.endPrice)
      } else {
        logisticMoney = 0
      }
      return logisticMoney.toFixed(2)
    },
    totalObj: {
      get: function () {
        let priceTotal = 0
        let weightTotal = 0
        for (let i = 0; i < this.checkedArr.length; i++) {
          priceTotal += this.checkedArr[i].price * this.checkedArr[i].num
          weightTotal += this.checkedArr[i].weight * this.checkedArr[i].num
        }
        return {
          priceTotal: priceTotal.toFixed(2),
          weightTotal: weightTotal.toFixed(2)
        }
      },
      set: function (val) {
        return val
      }
    },
    ...mapGetters([
      'userInfo',
      'logisticList'
    ])
  },
  data () {
    return {
      sortActive: 'sales_num-desc',
      sortArr: [
        {
          title: '价格',
          value: 'price',
          name: ['price-asc', 'price-desc']
        },
        {
          title: '重量',
          value: 'weight',
          name: ['weight-asc', 'weight-desc']
        },
        {
          title: '销量',
          value: 'sales_num',
          name: ['sales_num-asc', 'sales_num-desc']
        }
      ],
      // dispareStoreArrGoodsIds: ['GN201806015398274889', 'GN201809076715392338', 'GN201809086715395633', 'GN201809086715395652', 'GN201809086715395710', 'GN201809086715395722', 'GN201809126715432415'],
      dispareStoreArrGoodsIds: [],
      pageNo: 1,
      pageSize: 20,
      pageTotal: 0,
      goodsDataObj: {},
      goodsArr: [],
      checkedArr: [],
      timer: null
    }
  },
  watch: {
    sortActive () {
      this.pageNo = 1
      this.$refs.goodsWrap.scrollTop = 0
      this.getGoodsList()
    }
  },
  methods: {
    checked (activeName) { // 筛选条件的内容
      if (this.sortActive === activeName) {
        this.sortActive = 'sales_num-desc'
      } else {
        this.sortActive = activeName
      }
    },
    toTop () {
      let t = 5
      this.timer = setInterval(() => {
        let h = this.$refs.goodsWrap.scrollTop
        let s = Math.floor(-h / t)
        if (h <= 0) {
          clearInterval(this.timer)
        } else {
          this.$refs.goodsWrap.scrollTop = h + s
        }
      }, 30)
    },
    lookImg (url) {
      this.$lookImg.showSmall(url)
    },
    goWhere (router) {
      this.$router.push({ name: router })
    },
    getGoodsList (type) { // 获取商品列表
      this.$ajax.post('/api/productSet/getProductListSeller', {
        sortType: this.sortActive.split('-')[1],
        sortField: this.sortActive.split('-')[0],
        limit: this.pageSize,
        currPageNo: this.pageNo,
        canUseAccount: this.userInfo.userName
      }).then((data) => {
        if (data.data.code === '200') {
          let res = data.data.data
          this.goodsDataObj = res
          this.pageTotal = res.total
          let arr = []
          for (let i = 0; i < res.datas.length; i++) {
            arr.push({
              description: res.datas[i].description,
              formatDescription: res.datas[i].formatDescription,
              initNum: 1,
              lineThreshold: res.datas[i].lineThreshold,
              picList: res.datas[i].picList,
              price: res.datas[i].price,
              productId: res.datas[i].productId,
              productStatus: res.datas[i].productStatus,
              salesNum: res.datas[i].salesNum,
              statusDetail: res.datas[i].statusDetail,
              stockNum: res.datas[i].stockNum,
              title: res.datas[i].title,
              weight: res.datas[i].weight
            })
          }
          this.goodsArr = arr
          if (type === 'init') { // 初始默认一个商品
            this.initPackage()
          }
        } else {
          this.$message({
            message: data.data.message,
            type: 'warning'
          })
        }
      }).catch((err) => {
        console.error(err)
        this.$message({
          message: '生意太火爆了, 请稍后再试',
          type: 'error'
        })
      })
    },
    initPackage () { // 初始化一个商品
      if (this.goodsArr.length > 0) {
        let item = this.goodsArr[0]
        this.checkedArr = [{
          description: item.description,
          money: (item.price * 1).toFixed(2),
          num: 1,
          picList: item.picList,
          price: item.price,
          productId: item.productId,
          productName: item.title,
          weight: item.weight
        }]
      }
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getGoodsList()
      this.$refs.goodsBox.scrollIntoView()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.getGoodsList()
      this.$refs.goodsBox.scrollIntoView()
    },
    addPackage (item) { // 加入礼品包列表
      if ((this.totalObj.weightTotal - 0) + (item.weight - 0) > 20) {
        this.$message({
          message: '单个包裹重量上限为20KG',
          type: 'warning'
        })
      } else if (this.isDifferent(item.productId)) {
        this.$message({
          message: '手机周边的商品不能与其他商品混合购买哦',
          type: 'warning'
        })
      } else {
        let checked = this.checkedArr
        for (let i = 0; i < checked.length; i++) {
          if (checked[i].productId === item.productId) {
            checked[i].num += 1
            return false
          }
        }
        this.checkedArr.push({
          description: item.description,
          money: (item.price).toFixed(2),
          num: 1,
          picList: item.picList,
          price: item.price,
          productId: item.productId,
          productName: item.title,
          weight: item.weight
        })
      }
    },
    deleChecked (index) { // 删除已选中的礼品包商品
      this.checkedArr.splice(index, 1)
    },
    dele (item, index) { // 减少数量
      if (item.num > 1) {
        this.checkedArr[index].num--
      }
    },
    add (item, index) { // 增加数量
      if ((this.totalObj.weightTotal - 0) + (item.weight - 0) > 20) {
        this.$message({
          message: '单个包裹重量上限为20KG',
          type: 'warning'
        })
      } else {
        this.checkedArr[index].num++
      }
    },
    isDifferent (productId) { // 是否分仓的商品
      let bol = false
      for (let i = 0; i < this.checkedArr.length; i++) {
        if (this.dispareStoreArrGoodsIds.indexOf(this.checkedArr[i].productId) < 0) { // 无特殊商品
          if (this.dispareStoreArrGoodsIds.indexOf(productId) >= 0) { // 选择的为特殊商品
            bol = true
            break
          }
        } else { // 有特殊商品
          if (this.dispareStoreArrGoodsIds.indexOf(productId) < 0) { // 选择的为正常商品
            bol = true
            break
          }
        }
      }
      return bol
    },
    setCommonPackage () { // 设置为常用礼品包
      this.$emit('setCommonPackage', this.checkedArr)
    },
    toSamApplay () { // 样品申请
      this.sureAddPackage(999)
    },
    sureAddPackage (type) { // 确认添加礼品包套餐
      if (this.checkedArr.length === 0) {
        this.$message({
          message: '请选择商品至礼品包',
          type: 'warning'
        })
      } else {
        this.$ajax.post('/api/productSet/addSetTb', {
          sellerAccountId: this.userInfo.sellerAccountId,
          productIds: this.checkedArr
        }).then((data) => {
          if (data.data.code === '200') {
            if (type === 999) {
            } else {
              this.$message({
                message: '添加礼品包成功',
                type: 'success'
              })
            }
            let packages = {
              setId: data.data.data.setId,
              flagCommon: '0',
              productDetail: JSON.stringify(this.checkedArr) + '',
              productPrice: this.totalObj.priceTotal,
              sellerAccountId: this.userInfo.sellerAccountId,
              weight: this.totalObj.weightTotal,
              samPriceTotal: ((this.logisticPrice - 0) + (this.totalObj.priceTotal - 0)).toFixed(2)
            }
            this.setPackages(packages)
            this.$emit('addSuccess')
            if (type === 999) {
              this.$router.push({ name: 'samApplay' })
            }
          } else {
            this.$message({
              message: data.data.message,
              type: 'warning'
            })
          }
        }).catch((err) => {
          console.error(err)
          this.$message({
            message: '生意太火爆了, 请稍后再试',
            type: 'error'
          })
        })
      }
    },
    ...mapActions([
      'setPackages'
    ])
  },
  created () {
    this.getGoodsList('init')
  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../assets/stylus/index.styl'
.shopCarGift
  width 100%
  height 100%
  display flex
  overflow hidden
  transition all 0.3s
  .left
    flex 1
    overflow auto
    padding-right 5px
    .needGoods
      margin-bottom 10px
      img
        width 100%
    .goodsList
      .title
        display flex
        justify-content space-around
        fontSize($fontSize, 38px, $fontColor)
        background #eeeeee
        margin-bottom 30px
        strong
          position relative
          display inline-flex
          flex-direction column
          align-items center
          vertical-align middle
          cursor pointer
          width 20px
          height 34px
          text-align center
          vertical-align middle
          i
            position absolute
            width 0
            height 0
            border 5px solid transparent
            border-bottom-color #909399
            transition all 0.2s
          .top
            top 5px
          .bottom
            bottom 5px
            transform rotate(180deg)
          .active
            border-bottom-color $mainColor
      .goodsInfo
        display flex
        flex-wrap wrap
        justify-content space-between
        .empty
          border none
        li
          width 200px
          border 1px solid #F1F1F1
          margin-bottom 40px
          .imgBox
            height 200px
            line-height 200px
            display flex
            justify-content center
            align-items center
            margin-bottom 10px
            background #F4F4F4
            img
              width 100%
              height 100%
              max-height 100%
          p
            fontSize(12px, 18px, #666666)
            text-overflow ellipsis
            height 36px
            overflow hidden
            display box
            display -webkit-box
            -webkit-line-clamp 2
            -webkit-box-orient vertical
            padding 0 8px
          .bottom
            height 36px
            line-height 36px
            display flex
            justify-content space-between
            padding 0 8px 8px
            margin-top 8px
            .count
              flex 1
              i
                fontSize(12px, 18px, $mainColor)
              strong
                font-family 'dina'
                // src url('./DINALTERNATE.ttf') format('ttf')
                fontSize(22px, 26px, $mainColor)
                font-weight bold
            .joinCar
              width 36px
              height 36px
              line-height 36px
              border-radius 50%
              background $mainColor
              cursor pointer
              text-align center
              i
                // color #ffffff
                // fontSize(18px, 36px, #ffffff)
                display inline-block
                width 20px
                height 18px
                vertical-align middle
                background url('../../../assets/images/购物.png') no-repeat
                background-size 100% 100%
      .pager
        text-align center
        position relative
        .toTop
          position absolute
          top 0
          bottom 0
          right 0
          margin auto 0
          width 50px
          height 50px
          background $mainColor
          color #ffffff
          cursor pointer
          display flex
          flex-direction column
          justify-content center
          align-items center
          i
            font-size 30px
            line-height 30px
            font-weight bold
          span
            font-size 14px
            line-height 20px
  .right
    width 310px
    align-self flex-start
    margin-left 10px
    border 1px solid #D2D2D2
    background #FAFAFA
    padding-bottom 10px
    .titles
      display flex
      justify-content space-around
      span
        fontSize(12px, 30px, #666666)
        flex 1
        text-align center
    .chooseList
      max-height 450px
      overflow auto
      li
        display flex
        justify-content space-between
        align-items center
        height 80px
        margin-bottom 5px
        background #ffffff
        // padding 0 10px
        position relative
        >div
          flex 1
          text-align center
        img
          width 30px
          height 30px
        .noCont
          width 200px
          height 200px
        span
          fontSize(12px, 18px, #666666)
        .count
          display flex
          justify-content center
          align-items center
          text-align center
          i
            fontSize(14px, 18px, #aaaaaa)
            cursor pointer
          input
            width 30px
            outline none
            text-align center
            border none
        .dele
          position absolute
          top 5px
          right 5px
          fontSize(14px, 18px, #cccccc)
          cursor pointer
    .noCont
      text-align center
      margin 20px 0
    .mt120
      margin-top 5px
    .countMoneyBox
      padding 16px
      border-top 1px solid #E9E9E9
      p
        display flex
        justify-content space-between
        fontSize(14px, 18px, #999999)
        margin-bottom 7px
        span
          text-align right
          i
            color $mainColor
        strong
          text-align right
          color $mainColor
          font-weight bold
      .total
        font-size 20px
    .operateBtn
      padding 0 20px
      p
        display flex
        align-items center
        >span, >strong
          flex 1
          fontSize(18px, 48px, #ffffff)
          text-align center
          cursor pointer
        >span
          background #D38D1F
        >strong
          background $mainColor
      .setCommon
        fontSize(15px, 20px, $mainColor)
        margin-top 5px
        text-align right
        cursor pointer
</style>
